import {
  Card,
  List,
  PullToRefresh,
  Checkbox,
  SwipeAction,
  Dialog
} from 'antd-mobile'
import PsgCardItem from './PsgCardItem'
import styles from '../css/psg.module.css'
import { useSearchParams } from 'react-router-dom'
import { useMemo } from 'react'
import { deletePsgApi } from '../../../api/psg'

// 右侧 actions 的配置
const rightActions = [
  {
    key: 'delete',
    text: '删除',
    color: 'danger'
  }
]

function PsgCardList(props) {
  const [sp, setSP] = useSearchParams()
  const spObj = useMemo(() => Object.fromEntries(sp), [sp])

  const onRefresh = () => {
    setSP(spObj)
  }

  // 步骤3：每当复选框的选中状态发生变化，就触发这个函数，形参中的 arr 就是所有选中项的值
  const onCbGroupChange = (arr) => {
    // 把这个数组，通过子传父的方式，传入父组件中
    if (typeof props.onChange === 'function') {
      props.onChange(arr)
    }
  }

  const onAction = (action, id) => {
    if (action.key === 'delete') {
      // 删除数据
      Dialog.confirm({
        content: '确认删除吗？',
        async onConfirm() {
          await deletePsgApi(id)
          // 刷新页面数据
          setSP(spObj)
        }
      })
    }
  }

  return (
    <div className={styles.PsgCardList}>
      <Card title="下拉可刷新乘客列表">
        <PullToRefresh onRefresh={onRefresh}>
          {/* List 是列表容器组件 */}
          <List style={{ '--border-bottom': 'none', '--border-top': 'none' }}>
            {/* 步骤2：使用复选框组，把 map 循环包裹起来 */}
            <Checkbox.Group onChange={onCbGroupChange}>
              {/* 列表项 */}
              {props.list.map((item, index) => (
                <SwipeAction
                  key={index}
                  rightActions={rightActions}
                  onAction={(action) => onAction(action, item.id)}
                >
                  <PsgCardItem
                    key={index}
                    {...item}
                  />
                </SwipeAction>
              ))}
            </Checkbox.Group>
          </List>
        </PullToRefresh>
      </Card>
    </div>
  )
}

export default PsgCardList
